package MariMonDaily;

import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.TimeZone;

import com.dukascopy.api.IAccount;
import com.dukascopy.api.IBar;
import com.dukascopy.api.IChart;
import com.dukascopy.api.IConsole;
import com.dukascopy.api.IContext;
import com.dukascopy.api.IEngine;
import com.dukascopy.api.IHistory;
import com.dukascopy.api.IIndicators;
import com.dukascopy.api.IMessage;
import com.dukascopy.api.IOrder;
import com.dukascopy.api.IStrategy;
import com.dukascopy.api.ITick;
import com.dukascopy.api.Instrument;
import com.dukascopy.api.JFException;
import com.dukascopy.api.OfferSide;
import com.dukascopy.api.Period;

public class MariMon implements IStrategy {
	
	/// usual Jforex initialisers stuff
	private IConsole console;
    private IEngine engine;
    private IHistory history;
    private IOrder order;
    private IIndicators indicators;
    private IContext context;
    private IAccount account;
    private IChart chart;
    
    // setup list of instruments / symbols
    Set<Instrument> instruments = new HashSet<Instrument>();
	
	////
	

	public int MagicNumber = 199;
	public int slippage = 1;
	public double AdvertisedSpread = 5.0;
	public boolean UseFixedLot = true;
	public double FixedLot = 0.1;
	
	public double MACDMiniLevelToTrade = 0.0;
	public double SL_MAX = 300;
	public double StochLevelMaxToTrade = 70;
	public double StochH4LevelMax = 70;
	public double StochOBOSToMoveSL = 90;
	public double DeltaPipsMoveSLOnStoch = 10;
	public boolean UseCloseFriday = true;
	public boolean UseTakeProfitOn3MACD = true;
	public boolean UseFractalFilterToOpenTrades=false;
	public boolean UseStochD1slowToFilterTrade = true;
	public boolean UseStochH4ToTakeTrade = false;
	public boolean UseStochToConfirmCloseOn3MACD = true;
	public boolean UseHighLowCalcForMoveSLOnStoch = true;
	public double DeltaPipsFromSRZoneToTakeTrade = 250;
	public double NbHitMaxSRZoneToTakeTrade = 4;
	public double DeltaPipsInterMacdToClose = 5;
	public boolean UseRSI_W1_ToTrade = true;
	public double ValeurRSI_W1_ToTrade = 52;
	public boolean UseRSI_W1_ToCloseTrade = true;
	public double ValeurRSI_W1_ToCloseTrade = 70;
	
	public double DeltaPipsMA25 = 10; // In pips
	public int DeltaTimeLiveTrades = 86400;  // 24h in seconds.
	public int DeltaTimeHistoTrades = 14400; // 4h in seconds.
	public boolean BrokerHasSundayCandle = true;
	public double DistanceInterTrade = 10;  // In pips
	public double RequiredMarginPercentile = 1000;
	
	public static int PERIOD_D1 = 86400;  //CONSTANT FOR D1 IN SECONDS
	public int PERIOD_FRACTAL = PERIOD_D1;
	public int PERIOD_OSC = PERIOD_D1;
	
	/// jons own timeframe period for conversion to jforex
	public static Period TIMEFRAME_PERIOD;
	
	public static int PERIOD_H4 = 14400; // CONSTANT FOR H4 IN SECONDS;
	public int PERIOD_OSC_SMALL = PERIOD_H4;
	
	public static int PERIOD_W1 = 604800; // constant for W1 in seconds;
	public int PERIOD_RSI = PERIOD_W1;
	
	public int NbTradeMax = 3;
	
	// Steve shell mandatory variables
	private int O_R_Setting_max_retries = 10;
	private double O_R_Setting_sleep_time = 4.0; // seconds
	private double O_R_Setting_sleep_max = 15.0;
	private int RetryCount = 10;  // Will make this number of attempts to get around the trade context busy error?
	public boolean CriminalIsECN = true;
	private boolean TakingEmergencyAction;
	private int TicketNo = -1;
	private int OpenTrades;
	
	private boolean SignalBuy = false;
	private boolean SignalSell = false;
	private double lot;
	private String FractalSignal = "NONE";
	private boolean FlagCloseFriday = false;
	
	double PaireFractalValue[] = {0,0,0,0};
	double PaireFractalDate[] = {0,0,0,0};
	
	int myHour = 99;
	int  multiplier = 1;
	double spread = 0;
	int myMinute = 99;
	
	// Bods additional stuff and his own variables :-)
	String current_symbol = "";
	List<IOrder> Orders;
	
	
	@Override
	public void onStart(IContext context) throws JFException {
		// TODO Auto-generated method stub
		
		// first and foremost!
		Initialisation();
		
		
	}

	private void Initialisation() throws JFException {
		
		// Initialize standard JForex stuff

        engine = context.getEngine();
        history = context.getHistory();
        console = context.getConsole();
        account = context.getAccount();
        indicators = context.getIndicators();
        chart = context.getChart(Instrument.EURUSD);
        
        // get subscribed instruments
        instruments = get_instruments(); 

		
	
		
		DeltaPipsMA25 *= multiplier;
		DeltaPipsMoveSLOnStoch *= multiplier;
		DistanceInterTrade *= multiplier;
		SL_MAX *= multiplier;
		AdvertisedSpread *= multiplier;
		slippage *= multiplier;
		DeltaPipsFromSRZoneToTakeTrade *= multiplier;
		DeltaPipsInterMacdToClose *= multiplier;
		
		if (PERIOD_FRACTAL == 86400){
			TIMEFRAME_PERIOD = Period.DAILY;
		}
		if (PERIOD_FRACTAL == 14400){
			TIMEFRAME_PERIOD = Period.FOUR_HOURS;
		}

		
	}

	private Set<Instrument> get_instruments() throws JFException {
		// Just do GBPUSD for now.
		instruments.add(Instrument.GBPUSD);
		
		return instruments;
	}

	@Override
	public void onTick(Instrument instrument, ITick tick) throws JFException {
		// TODO Auto-generated method stub
		
		
		
		for (Instrument i : instruments){
			check_metals(i.toString());
		}
		
		// All main stuff done from here.
		start(instrument, tick);
		
	
		
	}

	private void start(Instrument instrument, ITick tick) throws JFException {
		 
		
		spread=0;
		
		boolean tradeallowedmargin = false;
		
		if (UseFixedLot == false){
			double accountBalance;
			accountBalance = account.getBalance();
			
			lot = accountBalance * 0.00004;
			
			if (lot < 0.01){
				// set to the minimum that lot can be.
				lot = 0.01;
			}
			else{
				lot = FixedLot;
			}
			
			boolean fractal1 = false;
			boolean fractal2 = false;
			boolean fractal3 = false;
			boolean fractal4 = false;
			
		
		
			
		}
		
		
		
	}

	private boolean NewBar(int TimeFrame, IBar bar) {
        long LastTime = 0;
        long currentBarTime;
        currentBarTime = bar.getTime();
        
        if (currentBarTime != LastTime){
        	LastTime = bar.getTime();
        	return true;
        }

		return false;
	}

	private boolean IsTesting() {
		// TODO Auto-generated method stub
		return false;
	}

//	private boolean is_valid_time(int myMinute) throws JFException {
//	    
//		long last_tick_time = history.getLastTick(Instrument.EURUSD).getTime();
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
//        // YOU WANT TO WORK WITH THE DATE OF THE LAST TICK IN CASE YOU ARE BACK TESWTING WITH HISTORICAL DATA
//        calendar.setTimeInMillis(last_tick_time);
//        //calendar.set(Calendar.HOUR_OF_DAY,from_hour);
//        calendar.set(Calendar.MINUTE, myMinute);
//        calendar.set(Calendar.SECOND, 0);
//        calendar.set(Calendar.MILLISECOND, 0);
//
//        
//
//        
//        // Check if time lies between specified range then Return the resulting boolean
//        boolean result = last_tick_time != myMinute;
//        return result;
//	}

	private void check_metals(String strInstrument) {
		
		current_symbol = strInstrument;
		
		// Check to see if current instrument is Gold or Silver and take action.
		if (current_symbol == "XAUUSD"){
			// assuming digits is going to be 4 for Jforex dukascopy
			multiplier = 100;
		}
		if (current_symbol == "XAGUSD"){
			multiplier = 100;
		}
		
	}



	@Override
	public void onBar(Instrument instrument, Period period, IBar askBar,
			IBar bidBar) throws JFException {

		
		if (NewBar(PERIOD_FRACTAL, askBar) == true){
			
			// loop 120 times
			for (int p = 0; p <= 120; p++){
					
				double FractalSlowDn = new Fractal().getFractal(PERIOD_FRACTAL, 6.0, -1, p, bidBar, TIMEFRAME_PERIOD);
				
			}
			
		}
		
	}



	@Override
	public void onMessage(IMessage message) throws JFException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onAccount(IAccount account) throws JFException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStop() throws JFException {
		// TODO Auto-generated method stub
		
	}

}
